<template>
  <!-- 打开嵌套表单的dialog -->
  <el-dialog :title="currentTitle" :visible.sync="dialogFormVisible">
    <el-form :model="formData" v-loading="isLoading">
      <el-form-item label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="formData.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色编码" :label-width="formLabelWidth">
        <el-input v-model="formData.code" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="描述" :label-width="formLabelWidth">
        <el-input type="textarea" v-model="formData.description"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit" :disabled="isLoading"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { getRole, saveOrUpdata } from "@/api/role";
export default {
  name: "RoleCreateOrEdit",
  data() {
    return {
      dialogFormVisible: false,
      isCreate: true,
      formData: {
        code: "",
        id: undefined,
        name: "",
        description: "",
      },
      isLoading: false,
      formLabelWidth: "120px",
    };
  },
  computed: {
    currentTitle() {
      return this.isCreate ? "添加角色" : "编辑角色";
    },
  },
  methods: {
    //初始化方法,展示或隐藏
    showAndInit(roleId) {
      this.formData.id = roleId;
      this.isCreate = !roleId;
      //可见
      this.dialogFormVisible = true;
      //添加或编辑逻辑代码
      if (this.isCreate) {
        //添加.把表单数据清空
        this.formData = {};
      } else {
        //编辑.显示要编辑的角色信息
        this.isLoading = true;
        getRole(roleId)
          .then((res) => {
            if (res.data.code === "000000") {
              const { id, name, code, description } = res.data.data;
              this.formData = { id, name, code, description };
            }
          })
          .finally(() => {
            this.isLoading = false;
          });
      }
    },
    //点击确定--提交数据
    onSubmit() {
      saveOrUpdata(this.formData).then((res) => {
        if (res.data.code === "000000") {
          this.$message.success(`${this.currentTitle}成功!`);
          this.dialogFormVisible = false;
          this.$emit("role-change");
        } else {
          this.$message.error(`执行${this.currentTitle}失败...`);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
